'use client';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { signUpUser } from '@/service/actions/user';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useState, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../ui/form';

const formSchema = z.object({
  username: z
    .string()
    .min(2, { message: '用户名至少2个字符' })
    .max(50, { message: '用户名最多50个字符' }),
  name: z
    .string()
    .min(2, { message: '昵称至少2个字符' })
    .max(50, { message: '昵称最多50个字符' }),
  email: z.string().email({ message: '邮箱格式不正确' }),
  password: z
    .string()
    .min(6, { message: '密码至少6个字符' })
    .max(50, { message: '密码最多50个字符' }),
  confirmPassword: z
    .string()
    .min(6, { message: '密码至少6个字符' })
    .max(50, { message: '密码最多50个字符' }),
});

export default function UserRegister() {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [open, setOpen] = useState(false);
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: '',
      name: '',
      email: '',
      password: '',
      confirmPassword: '',
    },
  });
  const { replace } = useRouter();

  const register = async (values: z.infer<typeof formSchema>) => {
    if (values.password !== values.confirmPassword)
      return toast({
        variant: 'destructive',
        title: '两次输入的密码不匹配',
      });
    startTransition(async () => {
      try {
        const { error } = await signUpUser({
          name: values.name,
          username: values.username,
          email: values.email,
          password: values.password,
        });
        if (error) {
          toast({
            variant: 'destructive',
            title: error.message,
          });
          return;
        }
        toast({
          title: '注册成功,请等待跳转...',
        });
        await authClient.signIn.username({
          username: values.username,
          password: values.password,
        });
        replace('/');
      } catch (error) {
        console.error(error);
        toast({
          variant: 'destructive',
          title: '注册失败,请重试',
        });
      }
    });
  };

  return (
    <Dialog open={open}>
      <DialogTrigger asChild>
        <span
          onClick={() => setOpen(true)}
          className="cursor-pointer hover:text-foreground"
        >
          用户注册
        </span>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>用户注册</DialogTitle>
          <DialogDescription>请填写以下信息以注册账户</DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(register)} className="space-y-2">
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>用户名</FormLabel>
                  <FormControl>
                    <Input placeholder="登录名" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>昵称</FormLabel>
                  <FormControl>
                    <Input placeholder="展示名" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>邮箱</FormLabel>
                  <FormControl>
                    <Input type="email" placeholder="邮箱" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>密码</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="输入密码" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="confirmPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>确认密码</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder="再次输入密码"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="flex justify-between pt-5">
              <Button
                type="button"
                variant="secondary"
                onClick={() => setOpen(false)}
              >
                取消
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending && (
                  <span className="animate-spin i-ri-loader-4-line" />
                )}
                注册
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
